<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" wrapClassName="modal-add"
    destroyOnClose>
    <BasicForm @register="registerForm"> </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref, h, reactive, watch } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, useForm } from '@/components/Form'
import { addRecordPrice, updateRecordPrice } from '@/api/sys/energyUnitPrice'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'

defineOptions({ name: 'ModalAddGroup' })

const emit = defineEmits(['success', 'register'])

const isUpdate = ref(false)
const currentData = ref()
const groupIndex = ref()
const groupData = ref([])

const validName = (rule, value, callback) => {
  let tagNames = groupData.value.map((item) => item.name)

  if (isUpdate.value) {
    const currentName = currentData.value.name
    tagNames = tagNames.filter((item) => item !== currentName)
  }

  return new Promise((resolve, reject) => {
    if (tagNames.includes(value)) {
      reject(new Error('已有重复分段名'))
    } else {
      resolve()
    }
  })
}

// 分段弹窗
const addGroupFormSchema: FormSchema[] = [
  {
    field: 'name',
    label: '分段名',
    component: 'Input',
    rules: [
      {
        required: true,
        validator: validName,
      },
    ],
  },
  {
    field: 'maxUsage',
    label: '最大用量',
    component: 'InputNumber',
    rules: [
      {
        required: true,
      },
    ],
  },
  {
    field: 'price',
    label: '分段价格',
    component: 'Input',
    rules: [
      {
        required: true,
      },
    ],
  },
  {
    field: 'period',
    label: '计价周期',
    component: 'Select',
    componentProps: {
      options: [
        { label: '每单位用量', value: 'DEFAULT' },
        { label: '每小时', value: 'HOUR' },
        { label: '每天', value: 'DAY' },
        { label: '每月', value: 'MONTH' },
        { label: '每年', value: 'YEAR' },
      ],
    },
    rules: [
      {
        required: true,
      },
    ],
  },
]

const [
  registerForm,
  { setFieldsValue, getFieldsValue, validateFields, updateSchema, resetFields, validate },
] = useForm({
  labelWidth: 140,
  baseColProps: { span: 24 },
  schemas: addGroupFormSchema,
  showActionButtonGroup: false,
  actionColOptions: {
    span: 23,
  },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields()
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate
  groupData.value = data.groupData

  if (unref(isUpdate)) {
    currentData.value = data.data
    groupIndex.value = data.index
    setFieldsValue({
      ...data.data,
    })
  } else {
    // 设置默认周期值
    setFieldsValue({
      period: data.period
    });
  }
})

const getTitle = computed(() => (!unref(isUpdate) ? '新增分段' : '修改分段'))

async function handleSubmit() {
  try {
    const values = await validate()
    let data = { values }
    if (unref(isUpdate)) {
      data = { ...data, groupIndex: unref(groupIndex) }
    }
    // 添加计价周期数据
    data = { ...data, period: values.period };
    setModalProps({ confirmLoading: true })
    message.success(isUpdate.value ? '修改成功' : '添加成功')
    closeModal()
    emit('success', { isUpdate: unref(isUpdate), data })
  } finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>
